package com.googlecode.battleofendor.synchroniation;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SocketConnection implements Connection {

	private ObjectOutputStream out;
	
	private ObjectInputStream in;
	
	public SocketConnection(Socket sock) throws IOException {
		out = new ObjectOutputStream(sock.getOutputStream());
		in = new ObjectInputStream(sock.getInputStream());
	}
	
	@Override
	public Object readObject() {
		try {
			// Auf Eingaben warten
			while(!Thread.interrupted()) {
				try {
					Object object = in.readObject();
					if(object == null) {
						continue;
					}
					return object;
				} catch(EOFException e) {
					try {
						Thread.sleep(100);
					} catch(InterruptedException ex) {
						return null;
					}
				}
			}
		} catch(ClassNotFoundException e) {
			System.err.println("Client and server do not have the same version.");
		} catch(IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void writeObject(Object object) {
		try {
			System.out.println("Sending: "  + object);
			out.writeObject(object);
			out.flush();
		} catch(IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
